import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Select } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import { getUserList, updateUser, getDepartmentList } from '../../services/api';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingUser, setEditingUser] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
    total: 0,
  });

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await getUserList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setUsers(response.data);
        setPagination(prev => ({
          ...prev,
          total: response.data.length
        }));
      } else {
        setUsers([]);
        setPagination(prev => ({
          ...prev,
          total: 0
        }));
        message.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
      setUsers([]);
      setPagination(prev => ({
        ...prev,
        total: 0
      }));
    }
    setLoading(false);
  };

  const fetchDepartments = async () => {
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
      } else {
        setDepartments([]);
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
    }
  };

  useEffect(() => {
    fetchUsers();
    fetchDepartments();
  }, []);

  const handleEdit = (record) => {
    setEditingUser(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const response = await updateUser(editingUser.uid, values);
      if (response.code === 200) {
        message.success('更新成功');
        setModalVisible(false);
        fetchUsers();
      } else {
        message.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'uid',
      key: 'uid',
    },
    {
      title: '用户名',
      dataIndex: 'uname',
      key: 'uname',
    },
    {
      title: '所属部门',
      dataIndex: 'depId',
      key: 'depId',
      render: (depId) => departments.find(d => d.depId === depId)?.depName || depId,
    },
    {
      title: '管理员',
      dataIndex: 'admin',
      key: 'admin',
      render: (admin) => admin === 'yes' ? '是' : '否',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <h2>用户管理</h2>
      <Table
        columns={columns}
        dataSource={users}
        loading={loading}
        rowKey="uid"
        pagination={pagination}
        onChange={handleTableChange}
      />

      <Modal
        title="编辑用户"
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="uname"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="depId"
            label="所属部门"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select>
              {departments.map(dept => (
                <Select.Option key={dept.depId} value={dept.depId}>
                  {dept.depName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="admin"
            label="管理员"
            rules={[{ required: true, message: '请选择是否为管理员' }]}
          >
            <Select>
              <Select.Option value="yes">是</Select.Option>
              <Select.Option value="no">否</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList; 